//
//  STRegisterController.m
//  ShaBaoOnLine
//
//  Created by huang yong on 16/7/7.
//  Copyright © 2016年 com.ShaBaoOnline.www. All rights reserved.
//

#import "STRegisterController.h"
#import "STLoginController.h"
#import "AppDelegate.h"

//#import "STNetworkRequest.h"
//#import "ScanViewController.h"
//#import "STTabBarController.h"
@interface STRegisterController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *userNameTF;
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;
@property (weak, nonatomic) IBOutlet UITextField *codeTF;
@property (weak, nonatomic) IBOutlet UITextField *pwdTF;
@property (weak, nonatomic) IBOutlet UITextField *sugesterTF;
@property (weak, nonatomic) IBOutlet UIButton *codeBtn;

//除掉前后空格的电话号码／密码／推荐密码／验证码
@property(nonatomic,strong)NSString *phoneNumStr;
@property(nonatomic,strong)NSString *passwordStr;
@property(nonatomic,strong)NSString *sugestPasswordStr;
@property(nonatomic,strong)NSString *codeStr;
@property(nonatomic,strong)NSString *picCodeStr;
@property(nonatomic,strong)NSString *userNameStr;

@end

@implementation STRegisterController

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置代理
    [self setDelegate];
}

- (void)setDelegate {
    _userNameTF.delegate = self;
    _phoneTF.delegate = self;
    _pwdTF.delegate = self;
    _codeTF.delegate = self;
    _pwdTF.delegate = self;
    _sugesterTF.delegate = self;
    
    NSArray *tfArr = @[_userNameTF,_phoneTF,_pwdTF,_pwdTF,_codeTF,_sugesterTF];
    for (UITextField *tf in tfArr) {
         [tf setFont:[UIFont systemFontOfSize:14]];
    }
}
#pragma mark ------------------------ 验证码
- (IBAction)getCodeButton:(UIButton *)sender {
//    if (!isNetworkConnected) {
//        [MBProgressHUD showError:@"请先打开您的网络连接"];
//        return;
//    }
//    
//    //除掉手机号前后空格
//    _phoneNumStr = [self.phoneTF.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
//    if (_phoneNumStr.length == 0) {
//        [MBProgressHUD showError:@"请输入手机号"];
//    }else{
//        
//        if (![_phoneNumStr validateMobile]) {
//            [MBProgressHUD showError:@"手机号错误"];
//            return ;
//        }
//        //获取验证码
//        [self timerCountDown];
//        [self loadData];
//        //记录点击了发送验证码按钮
//        _codeBtn.tag = 1;
//    }
}

#pragma mark ------------------------ 发送短信验证码
- (void)loadData{
    NSMutableDictionary *paramDict = [NSMutableDictionary dictionary];
    paramDict[@"mobileNo"] = _phoneNumStr;
    paramDict[@"type"] = @"register";
//    [[STNetworkRequest shareRequest] startGetRequest:@"triggerSms" parameter:paramDict showNetworkErrorAlert:YES onCompletion:^(id jsonResponse) {
//        int result = [[jsonResponse objectForKey:@"result"] intValue];
//        
//    } onError:^(id jsonResponse) {
//        
//    }];
}
#pragma mark ------------------------ 扫描二维码
- (IBAction)SugesterCodeAction:(UIButton *)sender {
    
//    ScanViewController *scanView = [[ScanViewController alloc] init];
//    UINavigationController *uic = [[UINavigationController alloc] initWithRootViewController:scanView];
//    scanView.vcTag = 1;
//    scanView.QRUrlBlock = ^(NSString *url){
//        self.sugesterTF.text = url;
//    };
//    [self presentViewController:uic animated:YES completion:nil];
}

#pragma mark ------------------------ 注册
- (IBAction)registerAction:(id)sender {
//    if (!isNetworkConnected) {
//        [MBProgressHUD showError:@"没有网络连接,无法注册"];
//        return;
//    }
//    _phoneNumStr = [self.phoneTF.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
//    _passwordStr = [self.pwdTF.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
//    _sugestPasswordStr = [self.sugesterTF.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
//    _codeStr = [self.codeTF.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
//    _userNameStr = [self.userNameTF.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
//    if (_userNameStr.length == 0) {
//        [MBProgressHUD showError:@"用户名不能为空"];
//        return;
//    }
//    
//    if (_phoneNumStr.length == 0) {
//        [MBProgressHUD showError:@"手机号不能为空"];
//        return ;
//    }
//    if (![_phoneNumStr validateMobile]) {
//        [MBProgressHUD showError:@"手机号错误"];
//        return ;
//    }
//    
//    if(0 != _sugestPasswordStr.length)
//    {
//        if (![_sugestPasswordStr validateMobile]) {
//            [MBProgressHUD showError:@"推荐人手机号错误"];
//            return ;
//        }
//    }
//    if (_codeBtn.tag!=1) {
//        [MBProgressHUD showError:@"请先发送验证码"];
//        return;
//    }
//    if (_codeStr.length == 0) {
//        [MBProgressHUD showError:@"验证码不能为空"];
//        return;
//    }
//    if (_passwordStr.length == 0) {
//        [MBProgressHUD showError:@"密码不能为空"];
//        return ;
//    }
//    if (![_passwordStr validatePassword]) {
//        [MBProgressHUD showError:@"密码必须大于5位且包含数字和字母"];
//        return;
//    }
//    [self.view endEditing:YES];
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    
//    [self registerRequest];
//    [[XMPPManager sharedManager] xmppManagerRegisterWithUserName:self.userNameTF.text password:self.pwdTF.text];

}

- (void)registerRequest{
//    NSMutableDictionary *paramDict = [NSMutableDictionary dictionary];
//    paramDict[@"userName"] = _userNameStr;
//    paramDict[@"password"] = [_passwordStr MD5];
//    paramDict[@"mobileNo"] = _phoneNumStr;
//    paramDict[@"code"] = _codeStr;
//    paramDict[@"userType"] = @2;
//    paramDict[@"upMobileNo"] = _sugestPasswordStr;
//    
//    [[STNetworkRequest shareRequest] startGetRequest:@"registerSalerUpMobile" parameter:paramDict showNetworkErrorAlert:YES onCompletion:^(id jsonResponse) {
//        [MBProgressHUD hideHUDForView:self.view animated:YES];
//        int result = [[jsonResponse objectForKey:@"result"] intValue];
//        if (result == 1) {
//            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//            [defaults setObject:self.phoneNumStr forKey:@"userName"];
//            [defaults setObject:@"" forKey:@"password"];
//            [defaults setObject:@(0) forKey:@"remember"];
//            
//            [MBProgressHUD showSuccess:@"注册成功"];
//                      [self.navigationController popViewControllerAnimated:YES];
//            
//        }
//
//        
//        }
//     
//   
//     onError:^(id jsonResponse) {
//        [MBProgressHUD hideHUDForView:self.view animated:YES];
//    }];
}

#pragma  mark-- UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if (textField == _userNameTF) {
        if (string.length == 0 ) {
            return YES;
        }
        if (textField.text.length - range.length + string.length > 20) {
            return NO;
        }
    }
    
    if (textField == _phoneTF) {
        if (string.length == 0 ) {
            return YES;
        }
        if (textField.text.length - range.length + string.length > 11) {
            return NO;
        }
    }
    if (textField == _codeTF) {
        if (string.length == 0) {
            return YES;
        }
        if (textField.text.length - range.length + string.length > 6) {
            return NO;
        }
    }
    if (textField == _pwdTF) {
        if (string.length == 0) {
            return YES;
        }
        if (textField.text.length - range.length + string.length > 20) {
            return NO;
        }
    }
    if (textField == _sugesterTF) {
        if (string.length == 0 ) {
            return YES;
        }
        if (textField.text.length - range.length + string.length > 11) {
            return NO;
        }
    }
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
//    if (self.userNameTF.text.length > 5) {
//        [MBProgressHUD showError:@"输入用户名（不超过5个字)"];
//        return;
//    }
//    if (![self.phoneTF.text validateMobile ]&& self.phoneTF.text.length > 0) {
//        [MBProgressHUD showError:@"输入正确的手机号"];
//        return;
//    }
//    if(![self.pwdTF.text validatePassword] && self.pwdTF.text.length > 0) {
//        [MBProgressHUD showError:@"输入正确的密码"];
//        return;
//        
//    }
//    if (![self.sugesterTF.text validateMobile ]&& self.sugesterTF.text.length > 0) {
//        [MBProgressHUD showError:@"输入正确的推荐手机号"];
//        return;
//    }
//    if (textField == self.codeTF && self.codeTF.text.length != 6 && self.codeTF.text.length > 0 && ![_codeTF.text validatePhoneCode]) {
//        [MBProgressHUD showError:@"输入正确的验证码"];
//        return;
//    }
}
#pragma mark ------------------------ 返回
- (IBAction)backLogin {
    STLoginController *loginVc = [[STLoginController alloc] init];
    [self.navigationController pushViewController:loginVc animated:YES];
//    [self dismissViewControllerAnimated:YES completion:nil];
}

//Countdown 倒计时
- (void)timerCountDown {
    __block int timeout = 60;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        if (timeout<=0) {
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                [_codeBtn  setUserInteractionEnabled:YES];
                [_codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
            });
        }else{
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.2d",seconds];
            if (timeout == 60) {
                strTime = @"60";
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDuration:1];
                [_codeBtn setTitle:[NSString stringWithFormat:@"%@秒",strTime] forState:UIControlStateNormal];
                [UIView commitAnimations];
                [_codeBtn  setUserInteractionEnabled:NO];
                
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}
@end
